import 'package:detect/widgets/other/custom_scroll_behavior.dart';
import 'package:flutter/material.dart';

class ScrollListener extends StatefulWidget {
  final ScrollBehavior behavior;
  final bool refreshOnScroll;
  final Widget Function(BuildContext context, ScrollController controller) builder;
  final bool Function(ScrollController controller, ScrollNotification? prev, ScrollNotification? current)? onNotification;

  const ScrollListener({
    super.key,
    required this.builder,
    this.refreshOnScroll = false,
    this.behavior = const CustomScrollBehavior(),
    this.onNotification,
  });

  @override
  State<ScrollListener> createState() => _ScrollListenerState();
}

class _ScrollListenerState extends State<ScrollListener> {
  final ScrollController _scrollController = ScrollController();
  ScrollNotification? _prev, _current;

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget child = widget.builder(context, _scrollController);
    assert(child is ScrollView || child is SingleChildScrollView);
    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        _current = notification;
        if (widget.refreshOnScroll) setState(() {});
        bool result = widget.onNotification?.call(_scrollController, _prev, _current) ?? false;
        _prev = notification;
        return result;
      },
      child: ScrollConfiguration(behavior: widget.behavior, child: child),
    );
  }
}
